package com.bw.i_video

import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.os.SystemClock
import android.util.Log
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Observer
import com.bw.i_video.startup.StartupOptimizationManager
import com.example.common.utils.Const
import com.therouter.TheRouter
import com.therouter.router.Route

class SplashScreenActivity : AppCompatActivity() {
    
    private var countDownTimer: CountDownTimer? = null
    private lateinit var tvCountdown: TextView
    private var startTime = 0L
    
    companion object {
        private const val TAG = "SplashScreenActivity"
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash_screen)
        
        startTime = SystemClock.elapsedRealtime()
        Log.d(TAG, "SplashScreenActivity 开始创建")
        
        // 初始化视图
        tvCountdown = findViewById(R.id.tv_countdown)
        
        // 等待冷启动优化完成
        waitForStartupOptimization()
    }
    

    
    /**
     * 等待冷启动优化完成
     */
    private fun waitForStartupOptimization() {
        Log.d(TAG, "等待冷启动优化完成...")
        
        // 检查是否已经完成
        if (StartupOptimizationManager.isOptimizationComplete()) {
            Log.d(TAG, "冷启动优化已完成，直接开始倒计时")
            startCountdown()
            return
        }
        
        // 监听冷启动优化完成事件
        StartupOptimizationManager.optimizationComplete.observe(this, Observer { event ->
            if (event.isSuccess) {
                Log.d(TAG, "收到冷启动优化完成通知: 耗时${event.optimizationTime}ms, 任务数${event.taskCount}, 开始倒计时")
                startCountdown()
            } else {
                Log.w(TAG, "冷启动优化失败，强制开始倒计时")
                startCountdown()
            }
        })
        
        // 设置超时保护，避免无限等待
        startTimeoutProtection()
    }
    
    /**
     * 启动超时保护
     * 如果冷启动优化超过一定时间没有完成，强制开始倒计时
     */
    private fun startTimeoutProtection() {
        android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
            if (!StartupOptimizationManager.isOptimizationComplete()) {
                Log.w(TAG, "冷启动优化超时，强制开始倒计时")
                startCountdown()
            }
        }, 8000) // 8秒超时保护
    }
    
    private fun startCountdown() {
        Log.d(TAG, "开始倒计时")
        
        // 显示logo.png背景，显示倒计时
        val backgroundImage = findViewById<android.widget.ImageView>(R.id.iv_background)
        backgroundImage.visibility = android.view.View.VISIBLE
        
        // 显示倒计时
        tvCountdown.visibility = android.view.View.VISIBLE
        tvCountdown.text = "4秒"
        
        countDownTimer = object : CountDownTimer(4000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val secondsLeft = (millisUntilFinished / 1000).toInt()
                tvCountdown.text = "${secondsLeft}秒"
                Log.d(TAG, "倒计时: ${secondsLeft}秒")
            }
            
            override fun onFinish() {
                Log.d(TAG, "倒计时完成，准备跳转")
                // 倒计时结束，跳转到MainActivity
                navigateToMainActivity()
            }
        }.start()
    }
    
    private fun navigateToMainActivity() {
        val totalTime = SystemClock.elapsedRealtime() - startTime
        Log.d(TAG, "SplashScreen完成，耗时: ${totalTime}ms")
        
        // 使用TheRouter跳转
        TheRouter.build(Const.ADDRESS_MAIN).navigation(this)
        
        // 销毁当前Activity，避免内存泄漏
        finish()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 取消倒计时，避免内存泄漏
        countDownTimer?.cancel()
        countDownTimer = null
        
        Log.d(TAG, "SplashScreenActivity 已销毁")
    }
}